package cn.sciento.core.convert.date;

import cn.sciento.core.convert.exception.DateConvertException;
import cn.sciento.core.oauth.CustomUserDetails;
import cn.sciento.core.oauth.DetailsHelper;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class DateConverter implements Converter<String, Date> {
    private static final Logger logger = LoggerFactory.getLogger(DateConverter.class);

    private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

    public Date convert(String date) {
        if (!StringUtils.hasText(date))
            return null;
        SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        CustomUserDetails details = DetailsHelper.getUserDetails();
        if (details != null && details.getTimeZone() != null)
            dateFormatGmt.setTimeZone(TimeZone.getTimeZone(details.getTimeZone()));
        try {
            return dateFormatGmt.parse(date);
        } catch (ParseException e) {
            logger.error(ExceptionUtils.getStackTrace(e));
            throw new DateConvertException(String.format("Can't convert %s to %s", date, "yyyy-MM-dd HH:mm:ss"), e);
        }
    }
}
